home *** CD-ROM | disk | FTP | other *** search
/ MacTech 1 to 12 / MacTech-vol-1-12.toast / Source / MacTech® Magazine / Volume 11 - 1995 / 11.02 Feb 95 / 11.02 Tip < prev    next >
Encoding:
Text File  |  1996-04-04  |  1.4 KB  |  40 lines  |  [TEXT/R*ch]

  1. Keeping The Ports Straight
  2. Saving and restoring the GrafPort is something that must be done a lot.  Suppose
  3. you needed to convert a Point to Local coordinates. You first have to set the
  4. GrafPort to the window who’s coordinates you want.  It might look like this:
  5.  
  6. void foo(WindowPtr myWindow, Point *thePoint) {
  7.   GrafPrt savedPort;         // declare a temporary variable
  8.   GetPort(&savedPort);       // remember the old port
  9.   SetPort(myWindow);         // point to the right window
  10.   GlobalToLocal(thePoint);   // do the work
  11.   SetPort(savedPort);        // restore the old port
  12. }
  13. Here’s a nifty C++ class to simplify things.  
  14. Put it all in one header file, PortSaver.h:
  15.  
  16. class PortSaver {
  17. public:
  18.   PortSaver(GrafPtr newPort = nil);
  19.   virtual ~PortSaver(void);
  20. private:
  21.   GrafPtr savedPort;
  22. };
  23. inline PortSaver::PortSaver(GrafPtr newPort) {
  24.   GetPort(&savedPort);  // remember the old port
  25.   if (newPort != nil)
  26.     SetPort(newPort);   // set the new port
  27. }
  28. inline PortSaver::~PortSaver(void) {
  29.   if (savedPort != nil)  // if there is an old port
  30.     SetPort(savedPort);  // restore it
  31. }
  32. // A macro that makes the PortSaver easier to use
  33. #define SETPORT(aPort)  PortSaver setTheCurrentPortTo(aPort)
  34. Here is the same routine using class PortSaver
  35.  
  36. void foo(WindowPtr myWindow, Point *thePoint) {
  37.   SETPORT(myWindow);       // point to the right window
  38.   GlobalToLocal(thePoint); // do the work
  39. }
  40.